package com.ophiux.pay.config;

import com.wechat.pay.java.core.Config;
import com.wechat.pay.java.core.RSAAutoCertificateConfig;
import com.wechat.pay.java.core.notification.NotificationConfig;
import com.wechat.pay.java.service.payments.jsapi.JsapiService;
import com.wechat.pay.java.service.payments.jsapi.JsapiServiceExtension;
import com.wechat.pay.java.service.refund.RefundService;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;

/**
 * @desc:
 * @author: hhl
 * @date：2023/3/23 15:21
 */
@Configuration
@ConfigurationProperties("ophiux.wechat")
@Data
public class WechatPayV3Properties {
    /**
     * 小程序appid
     */
    private String miniAppid = "";
    /**
     * 商户号
     */
    public String merchantId = "";
    /**
     * 商户API私钥路径
     */
    public String privateKeyPath = "";
    /**
     * 商户证书序列号
     */
    public String merchantSerialNumber = "";
    /**
     * 商户APIV3密钥
     */
    public String apiV3key = "";
    /**
     * 商户api证书私钥文件的私钥串，apiclient_key.pem文本形式打开即可获取，不需要前后缀
     */
    public String apiclientKey = "";
    /**
     * 支付回调通知地址
     */
    public String notifyUrl = "";

    /**
     * 退款通知地址
     */
    public String refundNotifyUrl="";

    private static Config config;

    @Bean("config")
    public Config config() {
        Config configBuilder = new RSAAutoCertificateConfig.Builder()
                .merchantId(merchantId)
                .privateKeyFromPath(privateKeyPath)
                .merchantSerialNumber(merchantSerialNumber)
                .apiV3Key(apiV3key).build();
        config = configBuilder;
        return configBuilder;
    }

    @Bean("jsapiService")
    @DependsOn("config")
    public JsapiService jsapiService() {
        JsapiService jsapiService = new JsapiService.Builder().config(config).build();
        return jsapiService;
    }

    @Bean("jsapiServiceExtension")
    @DependsOn("config")
    public JsapiServiceExtension jsapiServiceExtension() {
        JsapiServiceExtension jsapiServiceExtension = new JsapiServiceExtension.Builder()
                .config(config).build();
        return jsapiServiceExtension;
    }

    @Bean("notificationConfig")
    public NotificationConfig notificationConfig() {
        NotificationConfig notificationConfig = (NotificationConfig) config();
        return notificationConfig;
    }

    @Bean("refundService")
    @DependsOn("config")
    public RefundService refundService() {
        RefundService refundService = new RefundService.Builder().config(config).build();
        return refundService;
    }
}
